package com.rrqs.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.litesuits.http.request.content.multi.MultipartBody;
import com.litesuits.http.request.content.multi.StringPart;
import com.rrqs.activity.data.TimeLongResp;
import com.rrqs.net.AsyncHttpClient;
import com.rrqs.net.HttpResponseListener;
import com.rrqs.util.MyApplication;
import com.rrqs.utils.JsonUtils;
import com.rrqs.utils.LocationManger;
import com.zadtek.xmqishi.R;
import com.rrqs.activity.common.Common;
import com.rrqs.activity.common.Const;
import com.rrqs.activity.data.QiangDanData;
import com.rrqs.frame.JsonProcessHelper;

import static com.rrqs.activity.common.Const.TOURL;

/**
 * 我的定位
 *
 * @author Administrator
 */
public class MyLoaction extends Activity implements AMapLocationListener  {
    private ImageView backid;
    private TextView topview;
    private RelativeLayout locations;
    private TextView location_time, location_address, start;
    TextView myLocationText;

    private Address address;
    SimpleDateFormat formatter;
    Date curDate;

    OrderAsyncTask mOrderAsyn;
    private QiangDanData qiangdan;
    public static Handler mHandler;
    private SharedPreferences sp; // 用户信息缓存
    String Uid = "";

    MapView mMapView = null;
    // 声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;
    private LocationManager locationManager;


    private RecyclerView recyclerView;
    private PoiAdapter poiAdapter;
    private List<PoiItem> data = new LinkedList<>();
    private int currentPage = 1;

    private TextView tv_zaixian,tv_lixian;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylocation);
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);


        topview = (TextView) findViewById(R.id.topview);
        tv_lixian = (TextView) findViewById(R.id.tv_lixian);
        tv_zaixian = (TextView) findViewById(R.id.tv_zaixian);

        backid = (ImageView) findViewById(R.id.backid);
        topview = (TextView) findViewById(R.id.topview);
        topview.setText("定位");

        myLocationText = (TextView) findViewById(R.id.location_address);
        locations = (RelativeLayout) findViewById(R.id.location);
        start = (TextView) findViewById(R.id.start);
        location_time = (TextView) findViewById(R.id.location_time);
        location_address = (TextView) findViewById(R.id.location_address);

        GetLocation();

        mlocationClient = new AMapLocationClient(this);
        // 初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        // 设置定位监听
        mlocationClient.setLocationListener(this);
        // 设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
        // 设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        // 设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        // 启动定位
        mlocationClient.startLocation();

        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        Uid = sp.getString("uid", "");

        locations.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (Common.isNetworkConnected(MyLoaction.this)) {

                    if (mlocationClient != null && mlocationClient.isStarted()) {

                        Common.DisplayToast(MyLoaction.this, "定位成功", 1);
                    } else {
                        System.out.println("locClient is null or not started");
                    }
                } else {
                    Common.DisplayToast(MyLoaction.this, "通信失败,请检查网络!", 1);
                }
            }
        });

        backid.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                MyLoaction.this.finish();

            }
        });

        mHandler = new Handler() {
            @SuppressWarnings("unchecked")
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                switch (msg.what) {
                    case Const.STATE_START_SUCCESS://
                        qiangdan = new QiangDanData();
                        qiangdan = (QiangDanData) msg.obj;
                        if (qiangdan.getStatus().equals("0")) {

                            Common.DisplayToast(MyLoaction.this,
                                    qiangdan.getMessage(), 1);
                        }
                        break;
                    case Const.STATE_START_ERROR://
                        Common.DisplayToast(MyLoaction.this, "获取数据失败", 1);
                        break;
                }
            }
        };

        recyclerView = findViewById(R.id.recycleview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        poiAdapter = new PoiAdapter(R.layout.poi_address_item,data);
        recyclerView.setAdapter(poiAdapter);

        LocationManger.fetch(new LocationManger.OnLocationListener() {
            @Override
            public void onLocation(AMapLocation location) {
                String address = location.getCity()+location.getDistrict()+location.getStreet()+location.getAoiName();
                searchPoi(new LatLng(location.getLatitude(), location.getLongitude()));


                LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
                mMapView.getMap().addMarker(new MarkerOptions().position(latLng).snippet("DefaultMarker"));
                mMapView.getMap().moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                mMapView.getMap().moveCamera(CameraUpdateFactory.zoomTo(16));
//                CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(location.getAltitude(),location.getLongitude()),18,30,0));
            }
        });

        mMapView.getMap().setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(com.amap.api.maps.model.CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(com.amap.api.maps.model.CameraPosition cameraPosition) {
                mMapView.getMap().clear();
                LatLng latLng = cameraPosition.target;
                mMapView.getMap().addMarker(new MarkerOptions().position(latLng).snippet("DefaultMarker"));
                searchPoi(latLng);
            }
        });


        poiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PoiItem item = data.get(position);
                Intent intent = getIntent();
                intent.putExtra("addr",item.getProvinceName() + item.getCityName()+item.getAdName());
                intent.putExtra("detail",item.getSnippet()+item.getTitle());

            }
        });


        getToimeLong();
    }

    private void getToimeLong() {
        AsyncHttpClient  httpClient = new AsyncHttpClient(MyApplication.getInstace());

        SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        String uid = sp.getString("uid", "");

        MultipartBody body = new MultipartBody();
        body.addPart(new StringPart("emp_id", uid));
        body.addPart(new StringPart("ince", "get_qishi_timelong"));
        String url = TOURL + "";
        httpClient.post(url, body, new HttpResponseListener() {
            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);

            }

            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(String status, String result) {
                super.onSuccess(status, result);
                TimeLongResp resp = JsonUtils.json2Class(result,TimeLongResp.class);
                if (resp.getStatus() == 1){
                    tv_zaixian.setText(resp.getOnline());
                    tv_lixian.setText(resp.getOffline());
                }
            }
        });

    }



    class OrderAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String res = "";
            if (params[0].equals("qiangdan")) {// 更新坐标
                if (Const.latitude.length() > 0 && Const.lontitude.length() > 0
                        && !Const.latitude.equals("0")
                        && !Const.lontitude.equals("0")
                        && !Const.lontitude.contains("E")
                        && !Const.latitude.contains("E")) {
                    qiangdan = new QiangDanData();
                    qiangdan = JsonProcessHelper.jsonProcess_setEmpLocation(
                            "set_emp_location", Uid, Const.latitude,
                            Const.lontitude);// emp_id(快递ID)，lat(纬度)，lng(经度)


                    if (qiangdan != null) {
                        res = "state_success";
                    } else {
                        res = "mi_error";
                    }
                }
            }
            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result.equals("state_success")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_SUCCESS;
                msg.obj = qiangdan;
                mHandler.sendMessage(msg);
            } else if (result.equals("mi_error")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_ERROR;
                mHandler.sendMessage(msg);
            }
        }
    }

    private void GetLocation() {
        // 获取LocationManager服务
        locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        // 如果未设置位置源，打开GPS设置界面
        if (locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            start.setText("已开启");
            return;
        }
        start.setText("未开启");

    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                // 定位成功回调信息，设置相关消息
                // amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();// 获取纬度
                amapLocation.getLongitude();// 获取经度
                amapLocation.getAccuracy();// 获取精度信息
                if (amapLocation.getLatitude() > 0 && amapLocation.getLongitude() > 0) {

                    SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
                    String str = sdf.format(amapLocation.getTime());

                    location_time.setText(str + "   lbs   精确到10米");
                    myLocationText.setText(amapLocation.getAddress());
                    LatLng lng1 = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                    LatLng lng2 = new LatLng(Double.parseDouble(Const.latitude), Double.parseDouble(Const.lontitude));

                    LatLng latLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                    mMapView.getMap().addMarker(new MarkerOptions().position(latLng).snippet("DefaultMarker"));
                    mMapView.getMap().moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                    mMapView.getMap().moveCamera(CameraUpdateFactory.zoomTo(16));

                    float distance = AMapUtils.calculateLineDistance(lng1, lng2);
                    if (!Const.latitude.equals(amapLocation
                            .getLatitude() + "") && !Const.lontitude.equals(amapLocation
                            .getLongitude() + "")) {
                        Const.latitude = amapLocation.getLatitude() + "";
                        Const.lontitude = amapLocation.getLongitude() + "";


                        if (distance > 100) {
                            new OrderAsyncTask().execute("qiangdan");
                        }
                    }
                } else {
                    Common.DisplayToast(MyLoaction.this, "请再次定位", 1);
                }
            } else {
                Toast.makeText(MyLoaction.this, "定位失败,请检查网络!" + amapLocation.getErrorCode(),
                        Toast.LENGTH_SHORT).show();

            }
        }
    }

    @Override
    protected void onDestroy() {
        mlocationClient.stopLocation();
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    private void searchPoi(LatLng latLng) {
        PoiSearch.Query query = new PoiSearch.Query("", "", "");
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(MyLoaction.this, query);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latLng.latitude, latLng.longitude), 1000));
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if(i == 1000){
                    data.clear();
                    data.addAll(poiResult.getPois());
                    poiAdapter.notifyDataSetChanged();
                }else{
                    //ToastUtil.showToast(""+i);
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }


    private void searchPoi(String key) {
        PoiSearch.Query query = new PoiSearch.Query(key, "", LocationManger.location.getCity());
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(MyLoaction.this, query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if(i == 1000){
                    data.clear();
                    data.addAll(poiResult.getPois());
                    poiAdapter.notifyDataSetChanged();
                }else{
                    //ToastUtil.showToast(""+i);
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }


    class PoiAdapter extends BaseQuickAdapter<PoiItem,BaseViewHolder> {
        public PoiAdapter(int layoutResId, @Nullable List<PoiItem> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, PoiItem item) {
            String address = item.getCityName()+item.getAdName()+item.getSnippet()+item.getTitle();
            helper.setText(R.id.poi_address,address);
        }
    }
}
